{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### The power of `OpenAI function calling` 🚀  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import json\n",
    "import openai\n",
    "import requests\n",
    "from ast import literal_eval\n",
    "from IPython.display import JSON"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set environment variables\n",
    "os.environ['OPENAI_API_KEY'] = '...'\n",
    "os.environ['WEATHER_API_KEY'] = '...'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "open_ai_url = \"https://api.openai.com/v1/chat/completions\"\n",
    "model = \"gpt-3.5-turbo-0613\"\n",
    "user_message = \"What is the weather like in Delhi?\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/json": {
       "choices": [
        {
         "finish_reason": "function_call",
         "index": 0,
         "message": {
          "content": null,
          "function_call": {
           "arguments": "{\n  \"location\": \"Delhi\"\n}",
           "name": "get_current_weather"
          },
          "role": "assistant"
         }
        }
       ],
       "created": 1687324647,
       "id": "chatcmpl-7TkVbj3AUg1PJDGQOAqE3MNQQ3AP3",
       "model": "gpt-3.5-turbo-0613",
       "object": "chat.completion",
       "usage": {
        "completion_tokens": 17,
        "prompt_tokens": 82,
        "total_tokens": 99
       }
      },
      "text/plain": [
       "<IPython.core.display.JSON object>"
      ]
     },
     "execution_count": 4,
     "metadata": {
      "application/json": {
       "expanded": false,
       "root": "root"
      }
     },
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# A natural language request to the OpenAI API, asking about weather in delhi\n",
    "\n",
    "headers = {\n",
    "    \"Content-Type\": \"application/json\",\n",
    "    \"Authorization\": f\"Bearer {os.getenv('OPENAI_API_KEY')}\",\n",
    "}\n",
    "\n",
    "data = {\n",
    "   \"model\": model,\n",
    "   \"messages\":[\n",
    "      {\n",
    "         \"role\":\"user\",\n",
    "         \"content\": user_message\n",
    "      }\n",
    "   ],\n",
    "   \"functions\":[\n",
    "      {\n",
    "         \"name\":\"get_current_weather\",\n",
    "         \"description\":\"Get the current weather in a given location\",\n",
    "         \"parameters\":{\n",
    "            \"type\":\"object\",\n",
    "            \"properties\":{\n",
    "               \"location\":{\n",
    "                  \"type\":\"string\",\n",
    "                  \"description\":\"The city and state, e.g. San Francisco, CA\"\n",
    "               },\n",
    "               \"unit\":{\n",
    "                  \"type\":\"string\",\n",
    "                  \"enum\":[\n",
    "                     \"celsius\",\n",
    "                     \"fahrenheit\"\n",
    "                  ]\n",
    "               }\n",
    "            },\n",
    "            \"required\":[\n",
    "               \"location\"\n",
    "            ]\n",
    "         }\n",
    "      }\n",
    "   ]\n",
    "}\n",
    "\n",
    "response = requests.post(open_ai_url, headers=headers, data=json.dumps(data)).json()\n",
    "\n",
    "JSON(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/json": {
       "base": "stations",
       "clouds": {
        "all": 75
       },
       "cod": 200,
       "coord": {
        "lat": 28.6667,
        "lon": 77.2167
       },
       "dt": 1687324475,
       "id": 1273294,
       "main": {
        "feels_like": 308.94,
        "humidity": 84,
        "pressure": 1004,
        "temp": 302.2,
        "temp_max": 302.2,
        "temp_min": 302.2
       },
       "name": "Delhi",
       "sys": {
        "country": "IN",
        "id": 9165,
        "sunrise": 1687305220,
        "sunset": 1687355512,
        "type": 1
       },
       "timezone": 19800,
       "visibility": 3500,
       "weather": [
        {
         "description": "mist",
         "icon": "50d",
         "id": 701,
         "main": "Mist"
        }
       ],
       "wind": {
        "deg": 220,
        "speed": 1.54
       }
      },
      "text/plain": [
       "<IPython.core.display.JSON object>"
      ]
     },
     "execution_count": 12,
     "metadata": {
      "application/json": {
       "expanded": false,
       "root": "root"
      }
     },
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Based on the response above we extract the necessary information required to call Weather API\n",
    "arguments = response['choices'][0]['message']['function_call']['arguments']\n",
    "city = literal_eval(arguments)['location']\n",
    "\n",
    "base_url = f\"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={os.getenv('WEATHER_API_KEY')}\"\n",
    "\n",
    "weather_api_response = requests.get(base_url)\n",
    "weather_api_response = weather_api_response.json()\n",
    "\n",
    "JSON(weather_api_response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'id': 'chatcmpl-7TkYby42BwPDCBAnhKqpd0oAaZLPt', 'object': 'chat.completion', 'created': 1687324833, 'model': 'gpt-3.5-turbo-0613', 'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': 'The current weather in Delhi is misty. The temperature is 302.2 Kelvin (approximately 29.05 degrees Celsius) with a humidity of 84%. The visibility is 3500 meters.'}, 'finish_reason': 'stop'}], 'usage': {'prompt_tokens': 330, 'completion_tokens': 42, 'total_tokens': 372}}\n"
     ]
    }
   ],
   "source": [
    "# Converting the weather API response back to Natural Language\n",
    "\n",
    "headers = {\n",
    "    \"Content-Type\": \"application/json\",\n",
    "    \"Authorization\": f\"Bearer {os.getenv('OPENAI_API_KEY')}\",\n",
    "}\n",
    "\n",
    "data = {\n",
    "  \"model\": model,\n",
    "  \"messages\": [\n",
    "    {\"role\": \"user\", \"content\": user_message},\n",
    "    {\"role\": \"assistant\", \"content\": None, \"function_call\": {\"name\": \"get_current_weather\", \"arguments\": arguments}},\n",
    "    {\"role\": \"function\", \"name\": \"get_current_weather\", \"content\": str(weather_api_response)}\n",
    "  ],\n",
    "  \"functions\": [\n",
    "    {\n",
    "      \"name\": \"get_current_weather\",\n",
    "      \"description\": \"Get the current weather in a given location\",\n",
    "      \"parameters\": {\n",
    "        \"type\": \"object\",\n",
    "        \"properties\": {\n",
    "          \"location\": {\n",
    "            \"type\": \"string\",\n",
    "            \"description\": \"The city and state, e.g. San Francisco, CA\"\n",
    "          },\n",
    "          \"unit\": {\n",
    "            \"type\": \"string\",\n",
    "            \"enum\": [\"celsius\", \"fahrenheit\"]\n",
    "          }\n",
    "        },\n",
    "        \"required\": [\"location\"]\n",
    "      }\n",
    "    }\n",
    "  ]\n",
    "}\n",
    "\n",
    "response = requests.post(open_ai_url, headers=headers, data=json.dumps(data))\n",
    "\n",
    "print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The current weather in Delhi is misty. The temperature is 302.2 Kelvin (approximately 29.05 degrees Celsius) with a humidity of 84%. The visibility is 3500 meters.'"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.json()['choices'][0]['message']['content']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "env_twitter",
   "language": "python",
   "name": "env_twitter"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
